package com.wechat.backend.repository;

import com.wechat.backend.entity.Message;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface MessageRepository extends JpaRepository<Message, Long> {

    // 查询历史消息
    @Query("SELECT m FROM Message m WHERE " +
           "(m.fromId = :userId AND m.toId = :friendId) OR " +
           "(m.fromId = :friendId AND m.toId = :userId) " +
           "ORDER BY m.createTime ASC")
    List<Message> findHistory(@Param("userId") Integer userId, @Param("friendId") Integer friendId);

    // 查询未读消息数
    @Query("SELECT COUNT(m) FROM Message m WHERE m.fromId = :friendId AND m.toId = :userId AND m.status = 'unread'")
    int countUnread(@Param("userId") Integer userId, @Param("friendId") Integer friendId);

    // 标记为已读
    @Modifying
    @Query("UPDATE Message m SET m.status = 'read' WHERE m.fromId = :friendId AND m.toId = :userId AND m.status = 'unread'")
    int markAllAsRead(@Param("userId") Integer userId, @Param("friendId") Integer friendId);
} 